package com.liu.service.impl;


import com.liu.constant.RedisConstant;
import com.liu.entity.Activity;
import com.liu.mapper.ActivityMapper;
import com.liu.service.ActivityService;
import com.liu.service.GoodsService;
import com.liu.vo.ActivityVo;
import com.liu.vo.GoodsDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 活动service
 */
@Service
public class ActivityServiceImpl  implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public ActivityVo getActivityByGoodsId(Long goodsId) {
        //获取对应商品的秒杀活动信息
        Activity activity = activityMapper.selectByGoodsId(goodsId);

        if (activity == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ActivityVo activityVo = new ActivityVo();
        BeanUtils.copyProperties(activity, activityVo);
        activityVo.setActivityId(activity.getId());
        activityVo.setStartDate(sdf.format(activity.getStartDate()));
        activityVo.setEndDate(sdf.format(activity.getEndDate()));

        //判断当前时间是否秒杀活动即将开始或正在进行
        if (activity.getStartDate().after(new Date())) {
            activityVo.setActivityStatus(1);
        } else if (activity.getEndDate().before(new Date())) {
            activityVo.setActivityStatus(3);
        } else {
            activityVo.setActivityStatus(2);
        }
        return activityVo;
    }// 开始时间-----------------当前时间-----------------结束时间

    @Override
    public void publishActivity(Long activityId) {
        Activity activity = activityMapper.selectByPrimaryKey(activityId);
        Long goodsId = activity.getGoodsId();
        GoodsDetailVo goodsDetailVo = goodsService.getGoodsById(goodsId);
        Integer stockNum = goodsDetailVo.getStockNum();
        redisTemplate.opsForValue().set(RedisConstant.goodsStockDecre + goodsId, stockNum);
    }

}
